package iothub

import (
	"fmt"
	"github.com/mochi-mqtt/server/v2"
	"github.com/mochi-mqtt/server/v2/hooks/auth"
	"github.com/mochi-mqtt/server/v2/listeners"
	"go-iot-project/pkg/config"
	"go-iot-project/pkg/log"
)

var Server *mqtt.Server

func InitMqtt(mqttConfig *config.MqttConfig, hook mqtt.Hook) error {
	// 创建MQTT服务器
	Server = mqtt.New(nil)
	// 用户鉴权
	//var d = &auth.AllowHook{}
	//_ = Server.AddHook(d, nil)
	_ = Server.AddHook(hook, &auth.Options{
		Ledger: &auth.Ledger{
			Auth: auth.AuthRules{
				auth.AuthRule{
					Allow:    true,
					Password: auth.RString(mqttConfig.Password),
				},
			},
		},
	})

	tcp := listeners.NewTCP("tcp", fmt.Sprintf(":%d", mqttConfig.Port), nil)
	err := Server.AddListener(tcp)
	if err != nil {
		return err
	}

	if mqttConfig.WsPort > 0 {
		webSocket := listeners.NewWebsocket("ws", fmt.Sprintf(":%d", mqttConfig.WsPort), nil)
		err := Server.AddListener(webSocket)
		if err != nil {
			return err
		}
	}

	err = Server.Serve()
	if err != nil {
		log.Error(err)
	}
	return nil
}

func Close() {
	if Server != nil {
		err := Server.Close()
		if err != nil {
			log.Error(err)
			Server = nil
		}
	}
}
